from django.http import HttpResponse, JsonResponse
from django.shortcuts import render


# json.dumps()  字典转字符串
# json.loads()

# Create your views here.
def index(request):
    return HttpResponse('of')



def register(request,mobile):

    print(mobile)

    return HttpResponse('register')

# 4.GET请求--URL路径参数
def shop(request, pro_id, city_id):
    query_string = request.GET
    a = request.GET.get('name')
    print(a)
    # print(query_string)
    # a = query_string.get('name')  #
    # print(a)  # 12
    print('*' * 20)
    alist = query_string.getlist('name')
    print(type(alist))
    print(f'alist[0]:{alist[0]}')
    print(alist)  # ['panghu', '12'] 返回的是一个列表

    # 如果键不存在则返回None值，可以设置默认值进行后续处理
    b = query_string.get('b', 1)
    print(b)  # 1
    print(pro_id, city_id)

    return HttpResponse('shop')


def login(request):
    request_string = request.POST
    print(request_string)  # <QueryDict: {'name': ['panghu'], 'password': ['1234']}>
    print(type(request_string))

    return HttpResponse('login')


#######POST  -- JSON数据######################
def get_json(request):
    # json数据通过request.body来获取

    bytes_body = request.body.decode()
    """
    {
        "username":"panghu",
        "password":"123456"
    }
    <class 'str'>

    JSON形式的字符串
    """
    print(bytes_body)  # # b'{\n\t"name":"panghu",\n\t"password":123456\n}'
    print(type(bytes_body))  # <class 'bytes'>

    import json
    data = json.loads(bytes_body)  # {'name': 'panghu', 'password': 123456}
    print(data)
    print(type(data))  # <class 'dict'>
    print(data['name'])

    return HttpResponse('json')



########请求头##########################
def get_header_info(request):
    print(request.META)
    print(
        '*'*20
    )
    print(request.META['CONTENT_TYPE'])
    print(type(request.META))

    data = {
        'name': 'panghu'
    }
    import json
    data_str = json.dumps(data)
    return HttpResponse(data_str, content_type='application/json')

def json_data(request):

    dict1 = [{
        'name':'panghu',
        'password':111},
        {
            'name':'pang',
            'password':2
        }
    ]
    import json
    json_dict = json.dumps(dict1)
    # return JsonResponse(dict)
    return HttpResponse(json_dict,content_type='application/json')


def weibo(aaa):

    data = [{
        'name':'panghu',
        'password':123}
    ]
    # 如果用
    return JsonResponse(data,safe=False)



def set_cookie(request):
    username = request.GET.get('username')
    response = HttpResponse('set_cookie')
    response.set_cookie(key='username',value=username,max_age=24*3600)
    response.set_cookie(key='age',value=10,max_age=24*3600)
    response.set_cookie(key='address',value='bj',max_age=12*3600)

    return response


def get_cookie(request):

    # 如果不设置username获取到的是none
    username = request.COOKIES.get('username')
    print(username)

    return HttpResponse('get_cookie')

